package cn.ydxiaoshuai.workrecord;


import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;
import org.apache.pdfbox.printing.PDFPrintable;
import org.apache.pdfbox.printing.Scaling;

import javax.print.PrintService;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterJob;
import java.io.File;

/**
 * Description 打印工具类
 * ProjectName worktools
 * Created by 小帅丶 on 2023-01-17 17:16.
 * Version 1.0
 */

public class PrintUtil {
    //A4纸的宽高
    private static final Integer A4_WIDTH = 590;
    private static final Integer A4_HEIGHT = 840;
    private static final Integer X = 5;
    private static final Integer Y = 10;

    /**
     * 执行打印
     * @param pdfPath - 文件路径
     * @param printerName - 打印机名称
     * @Author 小帅丶
     * @Date  2023/1/17 18:21
     * @return org.apache.pdfbox.pdmodel.PDDocument
     **/
    public static PDDocument printPdf(String pdfPath, String printerName) throws Exception {
        File file = new File(pdfPath);
        PDDocument document = PDDocument.load(file);
        PrinterJob job = getPrintServiceByName(printerName);
        setPageStyle(document, job);
        // 开始打印
        job.print();
        return document;
    }
    /**
     * 设置打印纸风格
     * @Author 小帅丶
     * @Date  2023/1/17 18:26
     * @Param [document, job]
     * @return void
     **/
    private static void setPageStyle(PDDocument document, PrinterJob job) {
        job.setPageable(new PDFPageable(document));
        Paper paper = new Paper();
        // 设置打印纸张大小
        // 1/72 inch
        paper.setSize(A4_WIDTH,A4_HEIGHT);
        // 设置边距，单位是像素，10mm边距，对应 28px
        // 设置打印位置 坐标
        paper.setImageableArea(X,Y,A4_WIDTH,A4_HEIGHT);
        // custom page format
        PageFormat pageFormat = new PageFormat();
        pageFormat.setPaper(paper);
        // override the page format
        Book book = new Book();
        // append all pages 设置一些属性 是否缩放 打印张数等
        book.append(new PDFPrintable(document, Scaling.ACTUAL_SIZE), pageFormat, 1);
        job.setPageable(book);
    }

    /**
     * 查找打印机服务
     * @param printerName - 打印机名称
     * @Author 小帅丶
     * @Date  2023/1/17 18:22
     * @return java.awt.print.PrinterJob
     **/
    private static PrinterJob getPrintServiceByName(String printerName) throws Exception{
        PrinterJob printerJob = PrinterJob.getPrinterJob();
        boolean flag = false;
        for (PrintService printService : PrinterJob.lookupPrintServices()) {
            String name = printService.getName();
            if(name.contains(printerName)){
                System.out.println("找到打印机了~" + name);
                flag = true;
                printerJob.setPrintService(printService);
                break;
            }
        }
        if(!flag){
            throw new RuntimeException("打印失败,未找到名称为" + printerName + "的打印机,请检查.");
        }
        return printerJob;
    }

}
